package myTimer;

import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: tao
 * Date: 2023-12-05
 * Time: 12:43
 */
//通过这个类，来描述一个任务
class MyTimerTask implements Comparable<MyTimerTask>{
    //在什么时间点来执行任务
    private long time;//此处的time是一个ms级别的时间戳
    //实际任务要执行的代码
    private Runnable runnable;
    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        //计算的是要执行任务绝对时间，方便判断是否到达时间了
        this.time = System.currentTimeMillis() + delay;
    }
    //得到要执行任务时间的方法
    public long getTime() {
        return this.time;
    }
    public void run() {
        this.runnable.run();
    }
    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
}
//通过这个类表示定时器
class MyTimer {
    Object locker = new Object();
    //负责扫描任务队列，执行任务的线程
    private Thread t = null;
    //任务队列
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    //入队列的方法
    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            MyTimerTask task = new MyTimerTask(runnable, delay);
            queue.offer(task);
            locker.notify();
        }
    }
    //构造方法，会创建线程，让扫描线程来完成判定和执行
    public MyTimer() {
        t = new Thread(() -> {
            while (true) {
                try {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            //队列没有元素就要等待
                            locker.wait();
                        }
                        //取出元素，看是否到时间了
                        MyTimerTask task = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if(curTime >= task.getTime()) {
                            //到时间了，取出
                            queue.poll();
                            task.run();
                        } else {
                            //当前时间还没到，暂时不处理
                            locker.wait(task.getTime() - curTime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
public class TimerTest {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        }, 1000);
        System.out.println("hello main");
    }
}
